package com.itheima.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private Map map = new HashMap<>();

    public void init() {
        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword(passwordEncoder.encode("1234"));
        map.put(user1.getUsername(), user1);

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(passwordEncoder.encode("1234"));
        map.put(user2.getUsername(), user2);

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        init();

        User user = (User) map.get(username);

        ArrayList<GrantedAuthority> list = new ArrayList<>();

        if (user.getUsername().equals("zhangsan")) {
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        /*list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        list.add(new SimpleGrantedAuthority("add"));*/

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
    }

    /*public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode1 = passwordEncoder.encode("1234");
        String encode2 = passwordEncoder.encode("1234");
        System.out.println(encode1);
        System.out.println(encode2);

        boolean b1 = passwordEncoder.matches("1234", encode1);
        boolean b2 = passwordEncoder.matches("1234", encode2);
    }*/
}
